package com.wanlian.service.impl;

import com.wanlian.common.ConstantCode;
import com.wanlian.common.PageCondition;
import com.wanlian.common.RankType;
import com.wanlian.dao.*;
import com.wanlian.encrypt.MD5Utils;
import com.wanlian.entity.*;
import com.wanlian.error.ErrorCode;
import com.wanlian.error.SuccessCode;
import com.wanlian.model.ResultModel;
import com.wanlian.netty.msg.Device.model.Disk;
import com.wanlian.service.DeviceServices;
import com.wanlian.service.UserServices;
import com.wanlian.service.WordBookServices;
import com.wanlian.util.DateUtil;
import com.wanlian.util.StringUtil;
import com.wanlian.util.Utils;
import com.wanlian.vo.DeviceListVo;
import com.wanlian.vo.DeviceOptionVo;
import com.wanlian.vo.DeviceUpGradeVo;
import com.wanlian.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class DeviceServicesImpl implements DeviceServices {

    @Autowired
    public UserDao userDao;

    @Autowired
    public TaskDao taskDao;

    @Autowired
    public DeviceDao deviceDao;

    @Autowired
    public UserScoreDao userScoreDao;

    @Autowired
    public ScoreHistoryDao scoreHistoryDao;

    @Autowired
    public DeviceConfigDao deviceConfigDao;

    @Autowired
    public BlackListDao blackListDao;

    @Autowired
    public StorageDao storageDao;

    @Autowired
    public InviteDao inviteDao;

    @Autowired
    public UserServices userServices;

    @Autowired
    public WordBookServices wordBookServices;

    @Autowired
    public StorageItemDao storageItemDao;


    @Override
    public ResultModel doAdd(Device device) {
        ResultModel resultModel = new ResultModel();
        Device device1 = this.deviceDao.queryByDeviceId(device.getDeviceId());
        Device device2 = this.deviceDao.queryByMac(device.getMacAddress());
        if (device1 != null || device2 != null) {
            resultModel.setBresult(false);
            resultModel.setMessage(ErrorCode.DEVICE_EXIST);
        } else {
            device.setDevicekey(MD5Utils.MD5Encode(device.getMacAddress(), null));
            String name = device.getDeviceId().substring(device.getDeviceId().length() - 4, device.getDeviceId().length());
            device.setDeviceName("天翼链路由器" + name);
            deviceDao.add(device);
            //添加设备配置信息
            Device dbdevice = this.deviceDao.queryByDeviceId(device.getDeviceId());
            DeviceConfig deviceConfig = new DeviceConfig();
            deviceConfig.setDeviceId(dbdevice.getId());
            deviceConfigDao.add(deviceConfig);
            //添加云盘信息
            Storage storagedb = storageDao.queryByDeviceId(device.getDeviceId());
            if (storagedb == null) {
                Storage storage = new Storage();
                storage.setDeviceId(device.getDeviceId());
                storage.setOther(32 * 1024);
                storageDao.add(storage);
            }
            resultModel.setMessage(SuccessCode.SUCCESS_ADD);
            resultModel.setBresult(true);
        }
        return resultModel;
    }

    /**
     * 批量添加
     *
     * @param devices
     * @return
     */
    @Override
    public ResultModel doAdd(List<Device> devices) {
        ResultModel resultModel = new ResultModel(true);
        String msgs = "";
        for (Device device : devices) {
            Device device1 = this.deviceDao.queryByDeviceId(device.getDeviceId());
            Device device2 = this.deviceDao.queryByMac(device.getMacAddress());
            if (device1 != null || device2 != null) {
                msgs = msgs + device.getDeviceId() + ",";
            } else {
                String name = device.getDeviceId().substring(device.getDeviceId().length() - 4, device.getDeviceId().length());
                device.setDeviceName("天翼链路由器" + name);
                //device.setChannel(device.getChannel());
                // device.setDevicekey(Utils.getGuid());
                device.setDevicekey(MD5Utils.MD5Encode(device.getMacAddress(), null));
                deviceDao.add(device);
                //添加设备配置信息
                Device dbdevice = this.deviceDao.queryByDeviceId(device.getDeviceId());
                DeviceConfig deviceConfig = new DeviceConfig();
                deviceConfig.setDeviceId(dbdevice.getId());
                deviceConfigDao.add(deviceConfig);
                //添加云盘信息
                Storage storagedb = storageDao.queryByDeviceId(device.getDeviceId());
                if (storagedb == null) {
                    Storage storage = new Storage();
                    storage.setDeviceId(device.getDeviceId());
                    storage.setOther(32 * 1024);
                    storageDao.add(storage);
                }
            }
        }
        if (msgs.length() > 0) {
            msgs = "以下设备信息已存在，无法导入：" + msgs.substring(0, msgs.length() - 1);
        }
        resultModel.setBresult(true);
        resultModel.setMessage("导入成功!" + msgs);
        return resultModel;
    }

    @Override
    public ResultModel doUpd(List<Device> devices) {
        ResultModel resultModel = new ResultModel(true);
        String msgs = "";
        for (Device device : devices) {
            Device device1 = this.deviceDao.queryByDeMac(device.getDeviceId(), device.getMacAddress());
            if (device1 == null) {
                msgs = msgs + device.getDeviceId() + ",";
            } else {
                device1.setChannel(device.getChannel());
                deviceDao.add(device1);
            }

        }
        if (msgs.length() > 0) {
            msgs = "以下设备信息有误，无法修改：" + msgs.substring(0, msgs.length() - 1);
        }
        resultModel.setBresult(true);
        resultModel.setMessage("批量修改成功!" + msgs);
        return resultModel;
    }

    @Override
    public ResultModel doedit(Device device) {
        ResultModel resultModel = new ResultModel(true);
        Device devicem = deviceDao.queryByMacNot(device.getId(), device.getMacAddress());
        if (devicem != null) {
            resultModel.setBresult(false);
            resultModel.setMessage("mac地址已存在");
            return resultModel;
        }
        Device devicek = deviceDao.queryByDeviceKeyNot(device.getId(), device.getMacAddress());
        if (devicek != null) {
            resultModel.setBresult(false);
            resultModel.setMessage("devicekey已存在");
            return resultModel;
        }
        Device devicedb = deviceDao.queryById(device.getId());
        devicedb.setDevicekey(device.getDevicekey());
        devicedb.setMacAddress(device.getMacAddress());
        deviceDao.update(devicedb);
        resultModel.setMessage("修改成功");
        return resultModel;
    }

    @Override
    public ResultModel queryDevice(PageCondition pageCondition, int userId) {
        ResultModel resultModel = deviceDao.queryDeviceByParams(pageCondition, userId);
        return resultModel;
    }

    @Override
    public ResultModel queryDeviceByUser(Page page, int userId) {
        return deviceDao.queryDeviceByUser(page, userId);
    }


    @Override
    public List<Device> queryDevicesByUser(int userId) {
        return deviceDao.queryDevicesByUser(userId);
    }

    @Override
    public List<Device> queryDevicesOnline() {
        return deviceDao.queryDeviceOnline();
    }

    /**
     * 查询积分
     */
    @Override
    public ResultModel queryUserScoreByUserId(int userId) {
        ResultModel resultModel = new ResultModel();
        resultModel.setBresult(true);
        UserScore score = userScoreDao.queryUserScoreByUserId(userId);
        resultModel.setObject(score);
        return resultModel;
    }

    /**
     * 查询积分历史
     */
    @Override
    public ResultModel queryScoreHistoryByDeviceId(Page page, int deviceId) {
        return scoreHistoryDao.queryScoreHistoryByDeviceId(page, deviceId);
    }

    @Override
    public ResultModel doDeleteById(int deviceId) {
        Device device = this.deviceDao.queryById(deviceId);
        if (device != null) {
            return this.deviceDao.deleteById(deviceId);
        } else {
            ResultModel resultModel = new ResultModel(false);
            resultModel.setMessage(ErrorCode.DEVICE_NOTFINDID);
            return resultModel;
        }
    }

    @Override
    public ResultModel doDeleteByDeviceId(String deviceId) {
        return this.deviceDao.deleteByDeviceId(deviceId);
    }

    @Override
    public ResultModel bindDeviceById(int deviceId, int userId) {
        User user = this.userDao.queryById(userId);
        Device device = this.deviceDao.queryById(deviceId);
        if (user != null && device != null) {
            return this.deviceDao.bindDeviceById(deviceId, userId);
        } else {
            ResultModel resultModel = new ResultModel();
            resultModel.setBresult(false);
            resultModel.setMessage(ErrorCode.DEVICE_NOTFINDID);
            return resultModel;
        }
    }

    // todo：这里还需要判断设备是否存在的方法
    @Override
    public ResultModel doBindDeviceByDeviceKey(String deviceKey, int userId) {
        Device device = this.queryByDeviceKey(deviceKey);
        // device device = this.queryByMac(deviceId);
        ResultModel resultModel = new ResultModel();
        if (device == null) {
            resultModel.setBresult(false);
            resultModel.setMessage(ErrorCode.DEVICE_DEVICEID_NO_EXIST);
            return resultModel;
        }
        User user = this.userDao.queryById(userId);
        if (user != null) {
            Boolean hasBind = device.isHasBind();
            if (hasBind) {
                resultModel.setBresult(false);
                resultModel.setMessage(ErrorCode.DEVICE_HASBIND);
                return resultModel;
            } else {
                //判断设备是否禁用
                if (device.isEnable()) {
                    //查询是否有邀请送任务，若有则修改
                    Invite invite = inviteDao.queryUserByDUid(userId);
                    if (invite != null && device.isBindFirst()) {
                        if (invite.getCompleted() == false) {
                            if (!invite.getBindDevice()) {
                                invite.setBindDevice(true);
                                inviteDao.update(invite);
                            }
                            if (inviteDao.queryUserInvite(user.getId()) != null) {
                                userServices.inviteSend(invite, user);
                            }
                        }
                    }
                    //判断是否为淘宝或电信渠道获得，若是则赠送1000个int的int积分
                    String channel = device.getChannel();
                    if (device.isBindFirst()) {
                        if (channel != null && !channel.equals("")) {
                            //淘宝或电信渠道无法获得共享奖励
                            List<WordBook> online = wordBookServices.queryBooksByVal("online_channel");
                            String[] onlines = new String[online.size()];
                            for (int i = 0; i < online.size(); i++) {
                                onlines[i] = online.get(i).getWbval1();
                            }
                            if (Arrays.asList(onlines).contains(channel)) {
                                WordBook int_wordBook = wordBookServices.queryByVal("online_score");

                                float score = Float.parseFloat(int_wordBook.getWbval1());

                                UserScore userScore = userScoreDao.queryUserScoreByParams(userId, RankType.RANK_INT);
                                if (userScore == null) {
                                    UserScore userScore1 = new UserScore();
                                    userScore1.setModifyTime(DateUtil.currentTimestamp());
                                    userScore1.setUserId(userId);
                                    userScore1.setRankType(RankType.RANK_INT);
                                    userScore1.setScore(score);
                                    userScoreDao.add(userScore1);
                                } else {
                                    userScore.setScore(userScore.getScore() + score);
                                    userScoreDao.update(userScore);
                                }
                                ScoreHistory scoreHistory = new ScoreHistory();
                                scoreHistory.setDeviceId(device.getDeviceId());
                                scoreHistory.setUserId(userId);
                                scoreHistory.setTrantype(ConstantCode.TRANS_LINEINT);
                                scoreHistory.setRankType(RankType.RANK_INT);
                                scoreHistory.setAddTime(DateUtil.currentTimestamp());
                                scoreHistory.setScore(score);
                                scoreHistoryDao.add(scoreHistory);
                            }
                        }
                    }

                    return this.deviceDao.doBindDeviceByDeviceKey(deviceKey, userId);
                } else {
                    resultModel.setBresult(false);
                    resultModel.setMessage("禁用设备无法绑定");
                    return resultModel;
                }


            }
        } else {
            resultModel.setBresult(false);
            resultModel.setMessage(ErrorCode.DEVICE_NOTFINDID);
            return resultModel;
        }
    }


    @Override
    public Device queryByDeviceId(String deviceId) {
        return this.deviceDao.queryByDeviceId(deviceId);
    }

    @Override
    public Device queryByMac(String mac) {
        return this.deviceDao.queryByMac(mac);
    }


    /**
     * 获取设备昨日的积分历史
     *
     * @param page
     * @param deviceId
     * @return
     */
    @Override
    public ResultModel queryHistoryYestoryDayByDeviceId(Page page, int deviceId) {
        return scoreHistoryDao.queryHistoryYestoryDayByDeviceId(page, deviceId);
    }

    /**
     * 启动设备
     *
     * @param id
     * @return
     */
    @Override
    public ResultModel doEnableById(int id) {
        return this.deviceDao.doEnableById(id);
    }

    /**
     * 启用设备
     *
     * @param deviceId
     * @return
     */
    @Override
    public ResultModel doEnableByDeviceId(String deviceId) {
        return this.deviceDao.doEnableByDeviceId(deviceId);
    }

    /**
     * 添加设备配置
     *
     * @param config
     * @return
     */
    @Override
    public ResultModel doAddDeviceConfig(DeviceConfig config) {
        DeviceConfig dbConfig = deviceConfigDao.queryById(config.getDeviceId());
        if (dbConfig != null) {
            ResultModel resultModel = new ResultModel(false);
            resultModel.setMessage(ErrorCode.DEVICE_CONFIG_EXIST);
            return resultModel;
        } else {
            deviceConfigDao.add(config);
            ResultModel resultModel = new ResultModel(true);
            return resultModel;
        }
    }

    /**
     * 修改配置
     *
     * @param config
     * @return
     */
    @Override
    public ResultModel doEditDeviceConfig(DeviceConfig config, int userId) {
        Device device = deviceDao.queryCurrentByUserId(userId);
        DeviceConfig dbConfig = deviceConfigDao.queryByDevKey(device.getId());//queryById(config.getDeviceId());
        if (dbConfig == null) {
            ResultModel resultModel = new ResultModel(false);
            resultModel.setMessage(ErrorCode.DEVICE_CONFIG_NO_EXIST);
            return resultModel;
        } else {

            //修改2G网
            if (config.isHasTwoConfig()) {
                dbConfig.setHasTwoConfig(true);
                //   dbConfig.setHasFiveConfig(false);
                dbConfig.setTwoWifiAccount(config.getTwoWifiAccount());
                dbConfig.setTwoWifiPassWord(config.getTwoWifiPassWord());
                dbConfig.setTwoWifiForce(config.getTwoWifiForce());
                dbConfig.setTwoWifiLocktype(config.getTwoWifiLocktype());
            }
            //修改5g网
            if (config.isHasFiveConfig()) {
                //  dbConfig.setHasTwoConfig(false);
                dbConfig.setHasFiveConfig(true);
                dbConfig.setFiveAccount(config.getFiveAccount());
                dbConfig.setFiveWifiPassWord(config.getFiveWifiPassWord());
                dbConfig.setFiveWifiForce(config.getFiveWifiForce());
                dbConfig.setFiveWifiLocktype(config.getFiveWifiLocktype());
            }
            //修改访客网
            if (config.isHasCustomerConfig()) {
                //  dbConfig.setHasTwoConfig(false);
                dbConfig.setHasCustomerConfig(true);
                dbConfig.setCustomerWifiAccount(config.getCustomerWifiAccount());
                dbConfig.setCustomerWifiPassWord(config.getCustomerWifiPassWord());
                dbConfig.setCustomerWifiForce(config.getCustomerWifiForce());
                dbConfig.setCustomerWifiLocktype(config.getCustomerWifiLocktype());
            }
            //修改静态ip
            if (config.getSord() != null) {
                if (config.getSord().equals("static")) {
                    dbConfig.setSord(config.getSord());
                    dbConfig.setStatic_webAddress(config.getStatic_webAddress());
                    dbConfig.setStatic_subnetMask(config.getStatic_subnetMask());
                    dbConfig.setStatic_defaultNetWay(config.getStatic_defaultNetWay());
                    dbConfig.setOneDNS(config.getOneDNS());
                    dbConfig.setTwoDNS(config.getTwoDNS());
                }
                //修改动态ip
                if (config.getSord().equals("dhcp")) {
                    dbConfig.setSord(config.getSord());
                    dbConfig.setDynamicType(config.getDynamicType());
                    dbConfig.setOneDNS(config.getOneDNS());
                    dbConfig.setTwoDNS(config.getTwoDNS());
                }
            }
            this.deviceConfigDao.update(dbConfig);
            ResultModel resultModel = new ResultModel(true);
            resultModel.setMessage("设置成功");
            return resultModel;
        }
    }

    @Override
    public ResultModel queryDeviceMemoryConfig(int userId) {
        Device device = deviceDao.queryCurrentByUserId(userId);
        Storage storage = storageDao.queryByDeviceId(device.getDeviceId());
        Map<String, Object> map = new HashMap<String, Object>();
        float sum = (float) (storage.getShare() + storage.getOther()) / 1024;
        map.put("sum", (int) sum);
        map.put("share", storage.getShare() / 1024);
        ResultModel resultModel = new ResultModel(true);
        resultModel.setObject(map);
        return resultModel;
    }

    /**
     * 修改内存设置
     *
     * @param storage
     * @return
     */
    @Override
    public ResultModel doEditDeviceMemoryConfig(Storage storage, int userId) {
        Device device = deviceDao.queryCurrentByUserId(userId);
        DeviceConfig dbConfig = deviceConfigDao.queryByDevKey(device.getId());//queryById(config.getDeviceId());
        if (dbConfig == null) {
            ResultModel resultModel = new ResultModel(false);
            resultModel.setMessage(ErrorCode.DEVICE_CONFIG_NO_EXIST);
            return resultModel;
        }
        ResultModel resultModel = new ResultModel();
        Storage storagedb = storageDao.queryByDeviceId(device.getDeviceId());
        if (storage.getShare() * 1024 > storagedb.getShare() + storagedb.getOther()) {
            resultModel.setBresult(false);
            resultModel.setMessage("设置失败,共享容量超过总容量");
            return resultModel;
        }
        if (storage.getShare() < 16 && storage.getShare() > 0) {
            resultModel.setBresult(false);
            resultModel.setMessage("设置空间小于最小值16G,请重新设置！");
            return resultModel;
        }

        storagedb.setOther(storagedb.getOther() + storagedb.getShare() - storage.getShare() * 1024);
        storagedb.setShare(storage.getShare() * 1024);
        this.storageDao.update(storagedb);
        resultModel.setBresult(true);
        resultModel.setMessage("修改成功");
        return resultModel;
    }


    @Override
    public ResultModel doEditDeviceConfigCall(DeviceConfig config, int userId) {
        Device device = deviceDao.queryCurrentByUserId(userId);
        DeviceConfig dbConfig = deviceConfigDao.queryByDevKey(device.getId());//queryById(config.getDeviceId());
        if (dbConfig == null) {
            ResultModel resultModel = new ResultModel(false);
            resultModel.setMessage(ErrorCode.DEVICE_CONFIG_NO_EXIST);
            return resultModel;
        } else {
            dbConfig.setSord("pppoe");
            dbConfig.setNetworkAccount(config.getNetworkAccount());
            dbConfig.setNetworkPassWord(config.getNetworkPassWord());
            deviceConfigDao.update(dbConfig);
            //暂时保存数据库
            ResultModel resultModel = new ResultModel(true);
            resultModel.setMessage("正在连接");
            return resultModel;
        }
    }

    /**
     * 通过device 查看设备信息
     *
     * @param device
     * @return
     */
    @Override
    public ResultModel queryDeviceInfo(Device device) {
        DeviceOptionVo optionVo = new DeviceOptionVo();
        Device dbDevice = this.deviceDao.queryByDeviceId(device.getDeviceId());//queryById(Integer.parseInt(device.getDeviceId()));
        if (dbDevice == null) {
            dbDevice = this.queryByDeviceId(device.getDeviceId());
            if (dbDevice == null) {
                ResultModel resultModel = new ResultModel(false);
                resultModel.setMessage(ErrorCode.DEVICE_NO_EXIST);
                return resultModel;
            }
        }
        DeviceConfig deviceConfig = this.deviceConfigDao.queryByDevKey(dbDevice.getId());
        if (dbDevice.isHasBind()) {
            User user = userDao.queryById(dbDevice.getUserid());
            optionVo.setUser(user);
        }
        Storage storage = storageDao.queryByDeviceId(dbDevice.getDeviceId());
        optionVo.setStorage(storage);
        optionVo.setDevice(dbDevice);
        optionVo.setDeviceConfig(deviceConfig);
        return new ResultModel(true, optionVo);
    }


    @Override
    public ResultModel queryDeviceInfoApp(int userId) {
        DeviceOptionVo optionVo = new DeviceOptionVo();
        Device device = deviceDao.queryCurrentByUserId(userId);
        optionVo.setDevice(device);
        User user = userDao.queryById(userId);
        optionVo.setUser(user);
        DeviceConfig deviceConfig = deviceConfigDao.queryByDevKey(device.getId());
        optionVo.setDeviceConfig(deviceConfig);
        return new ResultModel(true, optionVo);
    }

    @Override
    public ResultModel queryUserDeviceCount(int userId) {
        long count = this.deviceDao.queryUserDeviceCount(userId);
        return new ResultModel(true, null, count);
    }

    @Override
    public ResultModel queryDeviceScoreHistoryByParam(PageCondition pageCondition, int userId) {
        return scoreHistoryDao.queryDeviceScoreHistoryByParam(pageCondition, userId);
    }

    @Override
    public Device queryDeviceByUserId(int userId) {
        return deviceDao.queryDeviceByUserId(userId);
    }

    @Override
    public ResultModel doSetDeviceCurrent(String deviceId, int userid) {
        deviceDao.doSetDeviceCurrent(deviceId, userid);
        Device device = deviceDao.queryCurrentByUserId(userid);
        device.setCurrent(false);
        deviceDao.update(device);
        Device devicedb = deviceDao.queryByDeviceId(deviceId);
        devicedb.setCurrent(true);
        deviceDao.update(devicedb);
        return new ResultModel(true, SuccessCode.DEVICE_CURRENT);
    }


    @Override
    public ResultModel doEditDevice(Device device, int userId) {
        String deviceId = device.getDeviceId();
        Device dbdevice;
        if (userId == 0) {
            dbdevice = deviceDao.queryByDeviceId(deviceId);
        } else {
            dbdevice = deviceDao.queryDeviceByUdid(deviceId, userId);
        }

        ResultModel resultModel = new ResultModel();
        if (dbdevice != null) {
            boolean isCurrent = dbdevice.isCurrent();
            //重置设备信息
            dbdevice.setUserid(0);
            dbdevice.setHasBind(false);
            dbdevice.setCurrent(false);
            dbdevice.setActive(false);
            deviceDao.update(dbdevice);
            //重置设备配置信息
            DeviceConfig deviceConfig = deviceConfigDao.queryByDevKey(dbdevice.getId());

            deviceConfig.setNetworkAccount(null);
            deviceConfig.setNetworkPassWord(null);

            String devicename = dbdevice.getDeviceId().substring(device.getDeviceId().length() - 4, device.getDeviceId().length() - 4);

            deviceConfig.setHasTwoConfig(true);
            deviceConfig.setTwoWifiAccount("TianYiLian-2.4G-" + devicename);
            deviceConfig.setTwoWifiPassWord(null);
            deviceConfig.setTwoWifiLocktype(null);
            deviceConfig.setTwoWifiForce(false);

            deviceConfig.setHasFiveConfig(true);
            deviceConfig.setFiveAccount("TianYiLian-5G-" + devicename);
            deviceConfig.getFiveWifiPassWord();
            deviceConfig.setFiveWifiForce(false);
            deviceConfig.setFiveWifiLocktype(null);

            deviceConfig.setHasCustomerConfig(false);
            deviceConfig.setCustomerWifiAccount(null);
            deviceConfig.setCustomerWifiPassWord(null);
            deviceConfig.setCustomerWifiLocktype(null);
            deviceConfig.setCustomerWifiForce(null);

            deviceConfig.setSord(null);

            deviceConfig.setStatic_defaultNetWay(null);
            deviceConfig.setStatic_subnetMask(null);
            deviceConfig.setStatic_webAddress(null);

            deviceConfig.setDynamicType(0);

            deviceConfig.setTwoDNS(null);
            deviceConfig.setOneDNS(null);

            deviceConfig.setdMemory(0);
            deviceConfig.setUsedMemory(0);
            deviceConfig.setUsedWMemory(0);
            deviceConfig.setwMemory(0);
            deviceConfig.setUsedWMemory(0);
            deviceConfig.setUsedMemory(0);
            deviceConfig.setMaxbandwidth(0);
            deviceConfigDao.update(deviceConfig);
            //若该用户有其他设备，则设置最近绑定一台设备为当前使用
            if (isCurrent) {
                List<Device> devices = deviceDao.queryAllByUserId(userId);
                if (devices.size() > 0) {
                    devices.get(0).setCurrent(true);
                    deviceDao.update(devices.get(0));
                }
            }
            //重置云盘信息
            Storage storage;
            if (userId == 0) {
                storage = storageDao.queryByDeviceId(dbdevice.getDeviceId());
            } else {
                storage = storageDao.queryByUserId(userId, dbdevice.getDeviceId());
            }
            storage.setTotal(32 * 1024 * 1024);
            storage.setOther(32 * 1024 * 1024);
            storage.setUserId(0);
            storage.setMovie(0);
            storage.setPhoto(0);
            storage.setMusic(0);
            storage.setShare(0);
            storage.setRemark(null);
            storageDao.update(storage);
            //滞空云盘子项
            List<StorageItem> storageItem = storageItemDao.queryUsersBySid(storage.getId());
            for (StorageItem storageItem1 : storageItem) {
                storageItemDao.delete(storageItem1.getId());
            }
            resultModel.setBresult(true);
            resultModel.setMessage(SuccessCode.DEVICE_NBIND);
        } else {
            resultModel.setBresult(false);
            resultModel.setMessage(ErrorCode.DEVICE_CONFIG_NO_EXIST);
        }
        return resultModel;
    }

    @Override
    public DeviceConfig queryDeviceConfig(int userId) {
        ResultModel resultModel = new ResultModel();
        Device device = deviceDao.queryCurrentByUserId(userId);
        DeviceConfig deviceConfig = null;
        if (device != null) {
            deviceConfig = deviceConfigDao.queryByDevKey(device.getId());
        }
        return deviceConfig;
    }

    @Override
    public ResultModel queryConfigInfo(int userId) {
        ResultModel resultModel = new ResultModel();
        Device device = deviceDao.queryCurrentByUserId(userId);
        if (device == null) {
            resultModel.setMessage("暂无设备");
            resultModel.setBresult(false);
            return resultModel;
        }
        DeviceConfig deviceConfig = deviceConfigDao.queryByDevKey(device.getId());
        //静态ip
        String sord = deviceConfig.getSord();
        String value = "";
        if (sord != null) {
            if (sord.equals("pppoe")) {
                value = "PPPOE";
            }
            if (sord.equals("static")) {
                value = "静态IP";
            }
            if (sord.equals("dhcp")) {
                value = "动态IP";
            }
        }
        //黑名单个数
        long count = blackListDao.queryCountById(device.getId());
        //是否设置共享内存
        Storage storage = storageDao.queryByDeviceId(device.getDeviceId());
        String share = "未设置";
        if (storage.getShare() > 0) {
            share = "";
        }

        //路由器版本号
        Map<String, String> map = new HashMap<String, String>();
        map.put("static_ip", value);
        map.put("blackcount", count + "");
        map.put("version", device.getVersion());
        map.put("sharedisk", share);
        resultModel.setBresult(true);
        resultModel.setObject(map);
        return resultModel;
    }


    @Override
    public ResultModel doEditOnline(Device device) {
        ResultModel resultModel = new ResultModel(true);
        Device devicedb = deviceDao.queryByDeviceKey(device.getDevicekey());
        devicedb.setOnline(device.isOnline());
        if (StringUtil.hasValue(device.getVersion())) {
            devicedb.setVersion(device.getVersion());
        }
        deviceDao.update(devicedb);
        return resultModel;
    }

    @Override
    public ResultModel editOnlineBatch(List<Device> devices) {
        ResultModel resultModel = new ResultModel(true);
      /*  DeviceListVo deviceListVo1=new DeviceListVo();
        List<device> device=deviceDao.queryDeviceOnline();
        for(device device1:device){
            device1.setVersion("qwertyui");
            device1.setOnline(false);
        }
        deviceListVo1.setDevices(device);*/
        deviceDao.EditBatchLine(devices);
        return resultModel;
    }

    @Override
    public ResultModel doEditStorage(Disk disk) {
        ResultModel resultModel = new ResultModel(true);
        Device device = deviceDao.queryByDeviceKey(disk.getDevicekey());
        if (device != null) {
            Storage storage = storageDao.queryByDeviceId(device.getDeviceId());
            storage.setShare(disk.getShare());
            storage.setTotal(disk.getTotal());
            storage.setOther(disk.getTotal() - disk.getShare());
            storageDao.update(storage);
            return resultModel;
        }
        return null;
    }

    @Override
    public ResultModel editOfflineAll() {
        ResultModel resultModel = new ResultModel(true);
        List<Device> devices = deviceDao.queryDeviceOnlineAll();
        List<Device> deviceList=new ArrayList<>();
        for (Device device : devices) {
            device.setOnline(false);
            deviceList.add(device);
       //     deviceDao.update(device);
        }
        deviceDao.EditBatch(deviceList);
        return resultModel;
    }

    @Override
    public Device queryByDeviceKey(String deviceKey) {
        return deviceDao.queryByDeviceKey(deviceKey);
    }
}
